<?php

namespace app\admin\controller\ad;

use app\common\controller\Backend;
use app\common\logic\AdHandler;
use think\Db;

/**
 * 广告项目管理
 *
 * @icon fa fa-circle-o
 */
class Ads extends Backend
{
    
    /**
     * Ads模型对象
     * @var \app\common\model\ad\Ads
     */
    protected $model = null;
    protected $multiFields = 'switch';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\ad\Ads;
        $this->view->assign("targetList", $this->model->getTargetList());
        $this->view->assign('ShowTypeList', $this->model->getShowTypeList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $rule = input('rule/s', 0);
        $mark = input('mark/s', '');
        $handler = AdHandler::init(['mark' => $mark, 'rule' => $rule]);

        if ($this->request->isAjax())
        {
            $buildparams = $this->buildparams();
            $result = $handler->first($buildparams);
            return json($result);
        }

        $this->assign([
            'mark' => $mark,
            'rule' => $rule
        ]);
        return $this->view->fetch('ad/tpl/index');
    }

    public function add()
    {
        $mark = input('mark/s', '');
        $rule = input('rule', '');

        if ($this->request->isAjax()) {
            $rules = $this->request->param('rules/a');
            $row = $this->request->param('row/a');

            AdHandler::init($rules)->add($row);

            $this->success('保存成功');
        }

        //规则标示和广告位置
        $this->assign([
            'mark' => $mark,
            'rule' => $rule,
            'insertRule' => AdHandler::init(['mark'=> $mark, 'rule'=> $rule])->insertRule()
        ]);

        return $this->view->fetch('ad/tpl/add');
    }


    public function edit($ids = null) {
        $row = $this->model->get($ids);
        $mark = input('mark/s', '');
        $rule = input('rule', '');
        if ($this->request->isAjax()) {
            $rules = $this->request->param('rules/a');
            $params = $this->request->param('row/a');

            AdHandler::init($rules)->edit($row, $params);

            $this->success('保存成功');
        }

        //规则标示和广告位置
        $this->assign([
            'mark' => $mark,
            'rule' => $rule,
            'row' => $row,
            'insertRule' => AdHandler::init(['mark'=> $mark, 'rule'=> $rule])->insertRule($ids)
        ]);
        return $this->view->fetch('ad/tpl/edit');
    }


}
